<template>
  <div class="course-add">
    <el-page-header @back="$goBack" :content="pageTitle" />
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="所属课程" prop="course_id" placeholder="请选择所属课程">
        <el-select v-model="form.course_id" style="width: 100%;">
          <el-option v-for="course in courses" :key="course.id" :value="course.id" :label="course.title" />
        </el-select>
      </el-form-item>
      <el-form-item label="目录名称(课程的章节)" prop="name">
        <el-input v-model="form.name" placeholder="请输入课程目录名称(章节名称)" />
      </el-form-item>
      <el-form-item label="该章节视频列表">
        <el-button type="danger" icon="el-icon-plus" size="mini" circle @click="addRow" />
        <xu-table :data="videos" :options="videoOptions" :pager="{ show: false }">
          <template slot="index" slot-scope="{ $index }">{{ $index + 1 }}</template>
          <template slot="name" slot-scope="{ row }">
            <el-input v-model="row.name" placeholder="请输入视频名称" />
          </template>
          <template slot="is_free" slot-scope="{ row }">
            <el-switch inactive-value="0" active-value="1" v-model="row.is_free" />
          </template>
          <template slot="url" slot-scope="{ row, $index }">
            <!-- 这里的上传视频，做成弹窗添加的那种 -->
            <template v-if="row.url">
              <el-input disabled :value="row.url" size="small" style="width: 150px; margin-right: 10px;" />
              <el-button size="small" type="warning" icon="el-icon-refresh-left" @click="showUpload(row, $index)">重新上传</el-button>
            </template>
            <el-button v-else type="primary" icon="el-icon-upload" size="small" @click="showUpload(row, $index)">上传视频</el-button>
          </template>
          <template slot="duration" slot-scope="{ row }">
            <el-input v-model="row.duration" placeholder="00:00:00" />
          </template>
        </xu-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">提交</el-button>
      </el-form-item>
    </el-form>

    <xu-upload-dialog v-model="showUploadDialog" @on-success="uploadSuccess" />
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { CourseActionsEnum } from '../../../_/vue/store/course'
import { CatalogActionsEnum } from '../../../_/vue/store/catalog'
import XuUploadDialog from '@/components/xu-upload-dialog'
export default {
  components: { XuUploadDialog },
  data () {
    return {
      id: '',
      loading: false,
      pageTitle: '添加课程目录',
      courses: [],
      form: {
        name: '',
        course_id: ''
      },
      rules: {
        course_id: [{ required: true, message: '请选择所属课程', trigger: 'blur' }],
        name: [{ required: true, message: '请输入课程目录名称(章节名称)' }]
      },
      // 显示上传弹窗
      showUploadDialog: false,
      // 当前选中上传的行
      currentRow: null,
      // 需要删除的 ids
      removeIds: [],

      // 视频列表
      videos: [],
      videoOptions: [
        { attrs: { label: '序号', prop: 'index', type: 'index' } },
        { attrs: { label: '视频名称', prop: 'name', width: '280px' } },
        { attrs: { label: '是否免费观看', prop: 'is_free', align: 'cetner', width: '120px' } },
        { attrs: { label: '视频地址', prop: 'url', width: '280px' } },
        { attrs: { label: '视频时长', prop: 'duration', align: 'center', width: '120px' } },
        {
          attrs: { label: '操作', prop: 'opt', align: 'center', width: '120px' },
          buttons: [
            { label: '添加', icon: 'el-icon-plus', type: 'primary', click: this.addRow },
            { label: '删除', icon: 'el-icon-delete', type: 'popover', click: this.removeRow }
          ]
        }
      ]
    }
  },
  async mounted () {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.pageTitle = '编辑课程目录'
      const { data } = await this.edit(this.id)
      this.form = data.baseInfo
      this.videos = data.videos
    }
    const result = await this.courseList()
    this.courses = result.data
  },
  methods: {
    ...mapActions({
      courseList: CourseActionsEnum.SELECT,
      store: CatalogActionsEnum.STORE,
      edit: CatalogActionsEnum.EDIT,
      save: CatalogActionsEnum.SAVE,
      delete: CatalogActionsEnum.DELETE
    }),
    showUpload (row, $index) {
      this.currentRow = { $index, row }
      this.showUploadDialog = true
    },
    uploadSuccess (res, file) {
      this.videos[this.currentRow.$index].url = res.data.url
    },
    addRow () {
      this.videos.push({
        name: '',
        is_free: 0,
        url: '',
        duration: ''
      })
    },
    removeRow (scope) {
      if (scope.row.id) {
        this.removeIds.push(scope.row.id)
      }
      this.videos.splice(scope.$index, 1)
    },
    validate () {
      const videos = this.videos
      for (let i = 0; i < videos.length; i++) {
        if (!videos[i].name) {
          this.$message.warning(`第${i + 1}的视频名称不能为空`)
          return false
        }
        if (!videos[i].url) {
          this.$message.warning(`第${i + 1}的视频文件不能为空`)
          return false
        }
        if (!videos[i].duration) {
          this.$message.warning(`第${i + 1}的视频时长不能为空`)
          return false
        }
      }
      return true
    },
    handleSubmit () {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          // 检测一下参数是否都是正确的，如果不正确，提示用户
          if (this.videos.length <= 0) {
            this.$message.warning('您还没有上传视频')
            return false
          }
          if (!this.validate()) {
            return false
          }
          try {
            this.loading = true
            if (this.id) {
              await this.save({ id: this.id, data: { ...this.form, videos: this.videos, _remove: this.removeIds } })
            } else {
              await this.store({ ...this.form, videos: this.videos })
            }
            this.$message.success('操作成功')
            this.$goBack()
          } catch (msg) {}
          this.loading = false
        }
        return false
      })
    }
  }
}
</script>
